import { JKManager } from "../../../JKCore/Script/JKManager";
import { LocalizedLabel } from "../../../JKCore/Script/Language/LocalizedLabel";
import { NormalViewBase } from "../../../JKCore/Script/View/NormalViewBase";

const { ccclass, property } = cc._decorator;

/**
 * 热更新界面
 */
@ccclass
export class HotUpdateView extends NormalViewBase {
    @property(cc.ProgressBar)
    pbFile: cc.ProgressBar = null
    @property(cc.ProgressBar)
    pbByte: cc.ProgressBar = null
    @property(LocalizedLabel)
    labUpdateInfo: LocalizedLabel = null
    @property(LocalizedLabel)
    labAppVersion: LocalizedLabel = null

    onLoad(): void {
        super.onLoad()
        cc.log(`${cc.js.getClassName(this)} onLoad`)

        // Ui
        this.pbFile.progress = 0
        this.pbFile.node.active = false
        this.pbByte.progress = 0
        this.pbByte.node.active = false
        this.labUpdateInfo.textKey = ``
        this.labAppVersion.textKey = `${JKManager.Language.getText(`ServerType${JKManager.AppConfig.ServerType}`)} ${JKManager.LocalStorage.getData(JKManager.LocalStorage.LocalStorageKey.AppVersion) || JKManager.AppConfig.AppVersion}`
    }

    init(data: any): void {
        cc.log(`${cc.js.getClassName(this)} init data = `, data)

        // Ui
        let dataUi = {
            fileProgress: 0,
            byteProgress: 0,
            updateEventInfo: null,
        }
        this._dataUpdateTool.put(JKManager.Const.HotUpdateView.CpntName.Ui, dataUi)

        if (CC_JSB) {
            JKManager.HotUpdate.init((info, event) => {
                this._onHotUpdateEvent(info, event)
            })
            JKManager.HotUpdate.checkUpdate()
        }
    }

    start(): void {
        cc.log(`${cc.js.getClassName(this)} start`)

        // Ui
        this._dataUpdateTool.registCpntUpdateWithName(JKManager.Const.HotUpdateView.CpntName.Ui, this._updateCpntUi.bind(this))
        this._updateCpntUi(this._dataUpdateTool.getCpntDataByName(JKManager.Const.HotUpdateView.CpntName.Ui), true)
    }

    update(dt: number): void {
        super.update(dt)
    }

    close(): void {
        cc.log(`${cc.js.getClassName(this)} close`)
    }

    onDestroy(): void {
        cc.log(`${cc.js.getClassName(this)} onDestroy`)

        JKManager.HotUpdate.clear()
    }

    // ====================================================================================
    // ===================================== 内部接口 ======================================
    // ====================================================================================

    /**
     * 刷新组件 Ui
     * @param data 数据对象
     * @param immediately 是否同步刷新
     */
    _updateCpntUi(data: { fileProgress: any; byteProgress: any; updateEventInfo: any; }, immediately: boolean = false) {
        cc.log(`${cc.js.getClassName(this)} _updateCpntUi data = `, data)

        this._taskQueueTool.addCmd({
            cmd: JKManager.Const.HotUpdateView.Cmd.UpdateCpntUi,
            params: {},
            call: (cmd, params) => {
                cc.log(`${cc.js.getClassName(this)} Cmd.UpdateCpntUi params = `, params)

                // data = {
                //     fileProgress: 0,
                //     byteProgress: 0,
                //     updateEventInfo: null,
                // }
                let fileProgress = data.fileProgress,
                    byteProgress = data.byteProgress,
                    updateEventInfo = data.updateEventInfo
                this.pbFile.progress = fileProgress
                this.pbFile.node.active = !!fileProgress
                this.pbByte.progress = byteProgress
                this.pbByte.node.active = !!byteProgress
                this.labUpdateInfo.textKey = updateEventInfo
                this.labAppVersion.textKey = JKManager.AppConfig.AppVersion

                this._taskQueueTool.doneCmd(cmd)
            }
        }, immediately)
    }

    // ====================================================================================

    /**
     * 热更事件回调
     * @param info 提示信息
     * @param event 事件对象
     */
    _onHotUpdateEvent(info: string, event: jsb.EventAssetsManager): void {
        cc.log(`${cc.js.getClassName(this)} _onHotUpdateEvent info = ${info} code = ${event.getEventCode()}`)

        // Ui
        let dataUi = this._dataUpdateTool.getCpntDataByName(JKManager.Const.HotUpdateView.CpntName.Ui)
        this._dataUpdateTool.setCpntDataByName(JKManager.Const.HotUpdateView.CpntName.Ui, {
            fileProgress: event.getPercentByFile() || dataUi.fileProgress,
            byteProgress: event.getPercent() || dataUi.byteProgress,
            updateEventInfo: info || event.getMessage() || dataUi.updateEventInfo,
        })

        switch (event.getEventCode()) {
            case jsb.EventAssetsManager.NEW_VERSION_FOUND:
                if (!JKManager.HotUpdate.isUpdating()) {
                    // 有热更准备有异步问题，必须延迟调用
                    this.scheduleOnce(() => {
                        JKManager.HotUpdate.hotUpdate()
                    }, 1.5)
                }

                break
            case jsb.EventAssetsManager.ALREADY_UP_TO_DATE:
                this.scheduleOnce(() => {
                    JKManager.UiManager.showNormalView(`Prefab/View/LaunchView/LaunchView`)
                }, 3)

                break

            default:
                break
        }
    }

    // ====================================================================================
    // ===================================== 外部接口 ======================================
    // ====================================================================================
}